package com.example.wearing.user;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.wearing.R;
import com.example.wearing.find.AddPostActivity;
import com.example.wearing.tools.ImageUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AlterUserImgActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "AlterUserImgActivity";

    public static final int RESQUEST_CODE_TAKE = 1;
    public static final int RESQUEST_CODE_CHOOSE = 2;
    private Handler handler;
    private ImageView alterImgBtn;

    private String username, u_imgBase64;
    private String imageUrl = "";
    private int userId;
    private String jdbcUrl, jdbcUser, jdbcPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alter_user_img);

        alterImgBtn = findViewById(R.id.alterImgBtn);
        //返回
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        //从SharedPreferences中获取用户名、用户头像
        SharedPreferences sp = this.getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        username = sp.getString("user_name","");
        u_imgBase64 = sp.getString("user_img","");
        userId = sp.getInt("user_id",0);
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");

        //设定头像
        Bitmap bitmap = ImageUtil.base64ToImage(u_imgBase64);
        alterImgBtn.setImageBitmap(bitmap);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        super.onOptionsItemSelected(item);
        return true;
    }

    //点击“保存”
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    public void saveImgBtn(View view){

        Toast.makeText(getApplicationContext(), "正在保存，请稍等~", Toast.LENGTH_SHORT).show();

        //上传数据到表中
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg){
                Log.i(TAG, "handleMessage: 收到消息");
                if(msg.what == 1){
                    //接收消息
                    int res = (int) msg.obj;
                    if(res == 1){
                        //发布成功
                        Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
                        //修改SharedPreferences中的用户头像
                        SharedPreferences sp = getApplicationContext().getSharedPreferences("user", Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("user_img",u_imgBase64);
                        editor.apply();

                        //返回"我的"界面
                        Intent intent = getIntent();
                        setResult(2, intent);
                        finish();
                    }else if(res == 2){
                        //发布失败
                        Toast.makeText(getApplicationContext(), "保存失败", Toast.LENGTH_SHORT).show();
                    }
                }
                super.handleMessage(msg);
            }
        };


        Thread thread = new Thread(this);
        thread.start();

    }

    //点击添加照片，弹出相册
    public void chooseImage(View view){

        Log.i(TAG, "onClick: 相册");
        //从相册选取照片
        if(ContextCompat.checkSelfPermission(AlterUserImgActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
            //真正去打开相册
            openAlbum();
        }else{
            //去申请权限
            ActivityCompat.requestPermissions(AlterUserImgActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }

    }

    //权限管理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 0) {
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                openAlbum();
            }else{
                Toast.makeText(this, "您没有获得访问相册权限~", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @SuppressLint("Range")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == RESQUEST_CODE_CHOOSE){
            //从相册选取照片
            Uri uri = data.getData();
            String path = null;
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if(cursor != null) {
                if(cursor.moveToFirst()) {
                    path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }
                cursor.close();
            }
            if(path != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                imageUrl = path;
                Log.i(TAG, "onActivityResult: path:"+path);///storage/emulated/0/DCIM/Camera/IMG_20220301_180527.jpg

                alterImgBtn.setImageBitmap(bitmap);
                String imageToBase64 = ImageUtil.imageToBase64(bitmap);
                u_imgBase64 = imageToBase64;
            }
        }
    }

    private void openAlbum(){
        Intent intent = new Intent("android.intent.action.PICK");
        intent.setType("image/*");
        startActivityForResult(intent, RESQUEST_CODE_CHOOSE);
    }


    //创建线程类，实现Runnable接口，用于存入数据库
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void run() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection cn = DriverManager.getConnection(jdbcUrl ,jdbcUser ,jdbcPassword);
            Statement st = (Statement)cn.createStatement();
            int updateCode;
            try {
                String updateSql = "UPDATE user set u_img = '"+ u_imgBase64 +"' where u_id="+userId;;
                int result = st.executeUpdate(updateSql);// 返回值代表收到影响的行数
                Log.i(TAG, "run: 更换头像修改数据成功"+result+"行----"+username);
                updateCode = 1;

            } catch (SQLException e) {
                updateCode = 2;
                Log.i(TAG, "run:SQL fail!!!__"+e);
                e.printStackTrace();
            }

            //发送消息
            Message msg = handler.obtainMessage(1, updateCode);
            handler.sendMessage(msg);
            Log.i(TAG, "run: 消息已发送---更新结果");

            st.close();
            cn.close();
        } catch (ClassNotFoundException | SQLException e) {
            Log.i(TAG, "run:SQL fail!!!__"+e);
            e.printStackTrace();
        }
    }


}